package com.bjsxt.chapter4_prototype;

import com.sun.xml.internal.messaging.saaj.util.ByteOutputStream;

import java.io.*;
import java.util.Date;

/**
 * @ClassName Client3
 * @Description 测试原型模式，深克隆
 * 通过序列化和反序列化的方式来实现深克隆
 * @Author 黑马程序员
 * @Date 11:06 2024/6/21
 * @Version 1.0
 **/
public class Client3 {
    public static void main(String[] args) {
        Date date = new Date(12312321331L);
        Sheep s1 = new Sheep(date, "少利");
        //Sheep s2 = (Sheep) s1.clone();
        Sheep s2 = null;
        ByteArrayOutputStream bos = null;
        ObjectOutputStream oos = null;
        ByteArrayInputStream bis = null;
        ObjectInputStream ois = null;
        try {
            // 使用序列化和反序列化实现深克隆
            bos = new ByteArrayOutputStream();
            oos = new ObjectOutputStream(bos);
            oos.writeObject(s1);
            byte[] bytes = bos.toByteArray();

            bis = new ByteArrayInputStream(bytes);
            ois = new ObjectInputStream(bis);
            // 克隆好的对象！
            s2 = (Sheep) ois.readObject();
            s2.setName("多利");

            System.out.println(s1);
            System.out.println(s1.getName());
            System.out.println(s1.getBirthDay());
            date.setTime(23423423423L);
            System.out.println(s1.getBirthDay());

            System.out.println(s2);
            System.out.println(s2.getName());
            System.out.println(s2.getBirthDay());
        } catch (IOException | ClassNotFoundException e) {
            e.printStackTrace();
        } finally {
            try {
                if (ois != null){
                    ois.close();
                }
                if (bis != null){
                    bis.close();
                }
                if (oos != null){
                    oos.close();
                }
                if (bos != null){
                    bos.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
